<?php
require_once('util/txt2array.php');
require_once('util/array2csv.php');

$stem = txt2Array("question/src1.txt");
$ans = txt2Array("answer/ans1.txt");

$stem = array_values(array_filter($stem, "trim"));
foreach ($stem as &$val) {
    $val = trim($val);
}

$stem = str_replace("\t", "", $stem);
$stem = preg_replace('/_{3,20}/', "_____", $stem);


$ans = array_values(array_filter($ans, "trim"));
$ans = str_replace("，", ";", $ans);
$ans = str_replace("，", ";", $ans);
$ans = str_replace("、", ".", $ans);
$ans = str_replace("\t", "", $ans);


$data = [];
$type = "";
$score = "0";
$level = "1";
$courseCode = "";

//处理题干
foreach ($stem as $item) {
    if (Operation::setStemType($item) || empty(Operation::$type)) {
        $score = Operation::getScore($item);
        continue;
    }

    if (!preg_match("/^[0-9]{1,2}[\.\．]/", $item)) {
        $idx1 = count($data) - 1;
        $data[$idx1][2] = $data[$idx1][2] . $item;
        continue;
    }
    $data[] = [Operation::$type, "", Operation::idxOff($item), "", "", "", $level, $score, $courseCode];
}

foreach ($data as &$val) {
    if ($val[0] == '填空题') {
        $val[2] = Operation::addUnderLine($val[2]);
    }
    if ($val[0] == '单选题') {
        $res = Operation::splitStemOptions($val[2]);
        $val[2] = $res[0];
        $val[3] = $res[1];;
    }
}


//处理答案
$ansMap = [];
$idx = 1;
$lastType = "";
foreach ($ans as $item) {
    if (Operation::setStemType($item) || empty(Operation::$type)) {
        continue;
    }
    if ($lastType != Operation::$type) {
        $idx = 1;
        $lastType = Operation::$type;
    }

    if (!preg_match("/^[0-9]{1,2}[\.\．]/", $item)) {
        $ansMap[Operation::$type . ($idx - 1)] = empty($ansMap[$idx - 1]) ? $item : $ansMap[$idx - 1] . $item;
        continue;
    }
    $ansMap[Operation::$type . $idx] = $item;
    $idx++;
}

foreach ($ansMap as $k => $v) {
    if (preg_match("/^单选题/", $k)) {
        preg_match_all("/[A-Za-z]/", $v, $ansSign);
        if (!empty($ansSign)) {
            foreach ($ansSign[0] as $k => $sign) {
                $ansMap["单选题" . ($k + 1)] = $sign;
            }
        }
    }
}

$idx = 1;
$lastType = "";
foreach ($data as &$v) {
    if ($lastType != $v[0]) {
        $idx = 1;
        $lastType = $v[0];
    }
    $v[4] = Operation::idxOff($ansMap[$v[0] . $idx]);
}

$file_name = "util\csv\西方经济学";
toCSV($file_name, $data, getHeaders());